#!/bin/sh
# install nodejs
set -euxo pipefail
CURDIR="$(cd "$(dirname "$0")" >/dev/null && pwd)"

function prepare(){
    echo "> prepare:"
    if [-e "/usr/bin/yum"]
    then 
        yum update
        yum install -y curl wget unar      
    else 
        apt update
        apt install -y curl wget unar    
    fi
}

function install(){
    echo "> Installing nodejs:"
    cd /opt/ && wget https://mirrors.huaweicloud.com/nodejs/latest-v12.x/node-v12.13.0-linux-x64.tar.gz
    unar node-v12.13.0-linux-x64.tar.gz -q 
    ln -s node-v12.13.0-linux-x64 node
    ln -s node/bin/node /usr/local/bin/node
    ln -s node/bin/npm /usr/local/bin/npm
    ln -s node/bin/npx /usr/local/bin/npx

    chmod 777 -R /opt/node/lib/node_modules

    echo "> rm node-v12.13.0-linux-x64.tar.gz"
    rm -f node-v12.13.0-linux-x64.tar.gz
}

function config(){
    echo "> Config Nodejs env:"
    chmod +x $CURDIR/nodejs_env.sh 
    bash $CURDIR/nodejs_env.sh

    echo "> 使用 huawei 镜像:"
    npm config set registry https://mirrors.huaweicloud.com/repository/npm/
    echo "> 设置 nodejs 工具的镜像地址:"
    npm config set disturl https://mirrors.huaweicloud.com/nodejs
    echo "> 设置 Node-Sass 的镜像地址:"
    npm config set sass_binary_site https://mirrors.huaweicloud.com/node-sass
    echo "> 设置浏览器引擎驱动镜像地址:"
    npm config set phantomjs_cdnurl https://mirrors.huaweicloud.com/phantomjs
    npm config set chromedriver_cdnurl https://mirrors.huaweicloud.com/chromedriver
    npm config set operadriver_cdnurl https://mirrors.huaweicloud.com/operadriver
    echo "> 设置 Electron 和 Python 的镜像地址:"
    npm config set electron_mirror https://mirrors.huaweicloud.com/electron/
    npm config set python_mirror https://mirrors.huaweicloud.com/python
    npm cache clean -f

    echo "> 使用 淘宝 cnpm:"
    npm install -g cnpm --registry=https://registry.npm.taobao.org

    # echo "> 安装 pm2:"
    # npm install -g pm2
    # echo "> pm2 list:"
    # pm2 list

    echo "> 查看当前设置的镜像地址:"
    npm config get registry
}

prepare
install
config
